package dmwr.web;

import dmwr.Dmwr;
import dmwr.bean.User;
import dmwr.service.Service.Duplicate;
import dmwr.util.Passwords;

public class UserAdmin {

	private static final int PAGE_SIZE = 15;

	public void list() {
		String page = Http.request().getParameter("page");
		int pageNum = page != null && page.length() > 0 ? Integer
				.parseInt(page) : 1;
		Http.request().setAttribute("page",
				Dmwr.service().listUsers(pageNum, PAGE_SIZE));
		Http.forward("/admin/user/list.jsp");
	}

	public void add() {
		Http.forward("/admin/user/form.jsp");
	}

	public void edit() {
		Http.request()
				.setAttribute(
						"item",
						Dmwr.service().getUser(
								Http.request().getParameter("username")));
		Http.forward("/admin/user/form.jsp");
	}

	public void save() {
		Long id = Http.request().getParameter("id") != null ? Long
				.parseLong(Http.request().getParameter("id")) : null;
		String password = Http.request().getParameter("password");
		byte[] salt = Passwords.salt();
		byte[] hash = Passwords.hash(password.toCharArray(), salt);
		User user = new User(id, Http.request().getParameter("username"), hash,
				salt, null, null, null);
		try {
			Dmwr.service().saveUser(user);
			Http.redirect("/admin/user");
		} catch (Duplicate e) {
			Http.redirect("/admin/user?edit=&username="
					+ ((User) e.getExisting()).getUsername());
		}
	}

	public void delete() {
		Dmwr.service().deleteUser(Http.request().getParameter("username"));
		Http.redirect("/admin/user");
	}
}